package top.infopub.mgr.hyp.service.impl;


import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.hyp.dao.HyRoleDao;
import top.infopub.mgr.hyp.dao.HyRolePurviewDao;
import top.infopub.mgr.hyp.service.HyPurviewService;
import top.infopub.mgr.hyp.service.HyRoleService;
import top.infopub.model.hy.Purview;
import top.infopub.model.hy.Role;
import top.infopub.model.hy.RolePurview;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;


@Service
public class HyRoleServiceImpl extends GenericServiceImpl<Role, String> implements HyRoleService {

    @Autowired
    private HyRoleDao roleDao;

    @Autowired
    private HyRolePurviewDao rolePurviewDao;

    @Autowired
    private HyPurviewService purviewService;

    @Override
    public GenericDao<Role, String> getDao() {
        return roleDao;
    }

    @Override
    public boolean isCodeExist(Role param) {
        return roleDao.isCodeExist(param) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String[] checkboxId) {
        for (String id : checkboxId) {
            rolePurviewDao.deleteByRoleId(id);
            roleDao.deleteByPrimaryKey(id);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRolePurview(String checkPurviewId, String roleId) {
        rolePurviewDao.deleteByRoleId(roleId);
        if (StringUtils.isNotBlank(checkPurviewId)) {
            String[] purIds = checkPurviewId.split(",");
            if (purIds != null && purIds.length > 0) {
                for (String purId : purIds) {
                    Purview purview = purviewService.selectByPrimaryKey(purId);
                    if (purview != null && purview.getId() != null) {
                        RolePurview rolepurview = new RolePurview();
                        rolepurview.setSpurviewId(purId);
                        rolepurview.setSroleId(roleId);
                        rolePurviewDao.insert(rolepurview);
                    }
                }
            }
        }
    }

    @Override
    public List<Role> selectOperatorNoCheckRole(String userId) {
        return roleDao.selectOperatorNoCheckRole(userId);
    }

    @Override
    public List<Role> selectByUserId(String userId) {
        return roleDao.selectByUserId(userId);
    }

    @Override
    public Page<Role> selectPageByDomainWhere(Page<Role> page, Role role) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<Role>)roleDao.selectByDomainWhere(role);
    }

}